package com.example.xzs.admin.userlogin.security;

import com.alibaba.fastjson.JSON;
import com.example.xzs.admin.userlogin.JsoResult.JsonResult;
import com.example.xzs.admin.userlogin.dao.repository.IUserRepository;
import com.example.xzs.admin.userlogin.enumerator.ServiceCode;
import com.example.xzs.admin.userlogin.ex.ServiceException;
import com.example.xzs.admin.userlogin.pojo.vo.UserLoginInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;

@Component
public class UserDetailsServiceImpl  implements UserDetailsService {

    @Autowired
    private IUserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserLoginInfoVo userLoginInfoVo=userRepository.selectUser(s);
        if(userLoginInfoVo==null){
            return null;
        }

        //        UserDetails userDetails= User.builder()
//                .username(loginInfoVO.getUsername())
//                .password(loginInfoVO.getPassword())
//                .disabled(loginInfoVO.getEnable()==0) //是否禁用
//                .accountLocked(false) //是否锁定
//                .accountExpired(false) //账号是否过期
//                .credentialsExpired(false) 登录i凭证是否过期
//                .authorities("山寨权限")//用户权限
//                .build();
        String role=userLoginInfoVo.getAdmin()==1?"ADMIN":"USER";
        Collection<GrantedAuthority> authorities=new ArrayList<>();
        GrantedAuthority authority=new SimpleGrantedAuthority(role);
        authorities.add(authority);
        UserLogDetails userDetails=new UserLogDetails(
                userLoginInfoVo.getUsername(),userLoginInfoVo.getPassword(),
                userLoginInfoVo.getEnable()==1, authorities, userLoginInfoVo.getId());
        return userDetails;
    }

}
